package ren.steve.system.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import ren.steve.system.custom.CustomMd5Password;
import ren.steve.system.filter.TokenAuthenticationFilter;
import ren.steve.system.filter.TokenLoginFilter;
import ren.steve.system.service.LoginLogService;

/**
 * @Author: CIS-T-13 Liu GuoJia
 * @Description:
 * @Date: Created in 2024/2/7 11:53
 */

@Configuration
@EnableWebSecurity                                           // 是开启SpringSecurity的默认行为
@EnableGlobalMethodSecurity(prePostEnabled = true)           // 开启注解功能, 默认禁止注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private UserDetailsService userDetailsService;

  @Autowired
  private CustomMd5Password customMd5Password;

  @Autowired
  private RedisTemplate redisTemplate;

  @Autowired
  private LoginLogService loginLogService;


  @Bean
  @Override
  protected AuthenticationManager authenticationManager () throws Exception {
    return super.authenticationManager();
  }

  // @Bean
  // public WebMvcConfigurer corsConfigurer() {
  //   return new WebMvcConfigurer() {
  //     @Override
  //     public void addCorsMappings(CorsRegistry registry) {
  //       registry.addMapping("/**")
  //         .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
  //         .allowedOrigins("*")                 // 允许所有来源，或者指定特定的来源
  //         .allowCredentials(true)              // 允许发送cookie
  //         .maxAge(3600);                       // 预检请求的有效期
  //     }
  //   };
  // }

  @Override
  protected void configure (HttpSecurity http) throws Exception {
    // 这里是配置关键, 决定哪些接口开启防护,哪些接口绕过防护
    http
      .csrf().disable()     // 禁用CSRF保护 开启跨域以便前后端API交互
      .cors()
      .and()
      .authorizeRequests()
      .antMatchers("/api/admin/login", "/api/admin/captcha").permitAll()   // 指定某些API不需要通过验证即可访问, 比如Login API
      .anyRequest().authenticated()   // 其他所有API需要认证才可以访问
      .and()
      // 之前 TokenAuthenticationFilter 放到 UsernamePasswordAuthenticationToken 的前面
      .addFilterBefore(new TokenAuthenticationFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class)
      // 认证过滤器
      .addFilter(new TokenLoginFilter(authenticationManager(), redisTemplate, loginLogService));
    // 禁用 session
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // 指定UserDetailService和加密器
    auth.userDetailsService(userDetailsService).passwordEncoder(customMd5Password);
  }

  /**
   * 配置哪些请求不拦截
   * 其中有排除 swagger 相关请求
   * @param web
   * @throws Exception
   */
  @Override
  public void configure (WebSecurity web) throws Exception {
    web.ignoring().antMatchers(
      "/favicon.ico",
      "/swagger-resources/**",
      "/webjars/**",
      "/v2/**",
      "/swagger-ui.html/**",
      "/doc.html*"
    );
  }
}
